<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class ProjectController extends RestController
{

    /**
     * 项目详情
     * @param type $id
     */
    public function actionDetail()
    {
        $data  = array('success' => 0);
        $id    = $this->_post('id');//project_id
        $model = Project::model()->findByPK($id);
        $projectBalance = Project::model()->getBalance($id);
        $info  = array(
            'projectId'       => $model->id,
            'name'            => $model->subTitle,
            'minInvestAmount' => $model->unitAmount,
            'incrementAmount' => $model->unitAmount,
            'interestFrom'    => $model->interestFrom,
            'statusCode'      => $model->status,
            'profitType'      => $model->repayment,
            'typeCode'        => $model->category3,
            'property'        => $model->property,
            'ratebegin'       => number_format($model->annualizedRate,2,'.',''),//年化收益率最低值
            'projectBalance'  => $projectBalance,
            'process'         => $this->converPoint($projectBalance, $model->amount),
            'investedNumber'  => $this->actiongetInvestedNum($id,$model->category3,0,$model->category1),
            'totalAmount'     => number_format($model->amount,0),
            'withdrawTip'     => '项目还款日17:00到达您草根账户；申请提现下一工作日到达银行卡',
            'additionalRate'  => $model->additionalRate*100,
        );
        $info['rateend'] = $info['ratebegin'];
        if ($model->endTime) {
            $info['reduceDay'] = round((strtotime($model->endTime) - strtotime(date('Y-m-d'))) / 3600 / 24) - $model->interestFrom + 1; //预期收益天数
            $info['reduceDay'] = $info['reduceDay']>0?$info['reduceDay']:0;
        }
        //解决缓存不一致
        if($projectBalance<=0 && $model->status==4)
        {
            $info['statusCode'] = 8;
            Yii::app()->cache_new->hdel('projectDetail',$id);
        }
        if($info['statusCode']==4 && $info['reduceDay'] > 61)
        {
            $info['transferDays'] = 60;
        }
        //解决缓存不一致
        if( strtotime($model->endTime) < time() && $model->status==8)
        {
            $info['statusCode'] = 9;
            Yii::app()->cache_new->hdel('projectDetail',$id);
        }
        $info['projectInterestList'][] = array(
            'rate'           => $info['ratebegin'],
            'min_invest'     => $model->unitAmount,
            'min_invest_des' => $this->showWan($model->unitAmount),
            'max_invest'     => $model->unitAmount,
            'max_invest_des' => $this->showWan($model->unitAmount),
        );
        $info['linkName']  = '新人赠送'.Yii::app()->params['register_reward_bonus']['number'].'元新人礼包';
        $info['linkUrl']   = 'http://mobile.cgtz.com/notice/index';
        $info['linkTitle'] = '新手奖励';
        if($this->checkUserToken($this->_post('user_id'),TOKEN) )
        {
            $user = User::model();
            if($user->invested($this->_post('user_id')))
            {
                $link = Yii::app()->cache_php->hget('MOBILE_APP_CONFIG','link');
                if($link)
                {
                    $link = json_decode($link);
                    if(strtotime($link->endTime) > time())
                    {
                        $info['linkName']  = $link->title;
                        $info['linkUrl']   = $link->url;
                        $info['linkTitle'] = $link->pageTitle;
                    }
                    else
                        unset($info['linkName'],$info['linkUrl']);
                }
                else
                    unset($info['linkName'],$info['linkUrl']);
            }
        }
        if($model->property == 9)
        {
            $config = Yii::app()->cache_php->get('appBaokuanConfig');
            if($config)
            {
                $config          = json_decode($config);
                // $info['icon']    = $config->icon;
                $welfare         = explode(PHP_EOL, $config->welfare);
                $welfare[0]      = trim($welfare[0]).(100*$model->additionalRate).'%;';
                $info['welfare'] = $welfare;
            }
        }
        unset($model);
        $data['data']    = $info;
        $data['success'] = 1;
        $this->setResult($data);
    }

    /**
     * 投资记录
     */
    public function actionInvestList()
    {
        $data      = array('success'=>0);
        $projectId = $this->_post('project_id');
        $page      = $this->_post('page',1);
        $pageSize  = $this->_post('pageSize',10);
        $cache     = Yii::app()->cache_new;
        Project::model()->tranlistIni($projectId);
        $count = $cache->llen('projectTransList.'.$projectId);
        $data['list']['totalCount'] = $count;
        $data['list']['pageNum']    = (int)(($count+$pageSize-1)/$pageSize);
        $data['success'] = 1 ;
        $rows = $cache->lrange('projectTransList.'.$projectId,($page-1)*$pageSize,$page*$pageSize-1);
        foreach($rows as $v)
        {
            $v = json_decode($v);
            $data['list']['pageList'][] = array(
                'invest_amount'   => $v->invest_amount,
                'annualized_rate' => $v->annualized_rate,
                'mobile'          => Helper::startReplace($v->username,'*',3,4),
                'time'            => $v->time,
            );
        }
        $this->setResult($data);
    }

    public function loadModel($Id)
    {
        return Project::model()->findByPK($Id);
    }

    /**
     * 精品推荐
     */
    public function actionGetRcommendProject()
    {
        $spentTime = number_format((microtime(true) - YII_BEGIN_TIME)*1000,2);
        Yii::log('to before controller deal spent '.$spentTime.' ms','info','api.performance.info');
        $user_id = $this->_post('user_id');
        $token   = $this->_post('token');
        $data    = Project::model()->getRecommendProject($user_id,$token);
        $spentTime = number_format((microtime(true) - YII_BEGIN_TIME)*1000,2);
        Yii::log('to recommend end spent '.$spentTime.' ms','info','api.performance.info');
        $this->setResult($data);
    }
     /* 获取项目列表
     */
    public function actionLoadProject()
    {
        $statusCode = $this->_post('code');
        $page       = $this->_post('page',1);
        $limit      = $this->_post('limit',5);
        $results    = HttpLib::post($this->javaApi['project_query'],array('limit'=>$limit,'page'=>$page,'status_code'=>$statusCode));
        $data = array('success'=>0,'msg'=>$results->errorMsg);
        if($results->success)
        {
            $list = array();
            if($results->result->pageList)
            {
                $ids = array();
                $pipe = Yii::app()->cache2->pipeline();
                foreach($results->result->pageList as $pagelist)
                    $pipe->get($pagelist->projectId .".Investable");
                $balances = $pipe->exec();
                foreach($results->result->pageList as $k=>$pageList)
                {
                    $pageList->projectBalance = (int)$balances[$k];
                    $pageList->procress = $this->converPoint($pageList->projectBalance, $pageList->totalAmount);
                    $pageList->min_rate = $pageList->min_rate;
                    $pageList->max_rate = $pageList->max_rate;
                    if ($pageList->endTime)
                    {
                        $pageList->reduceDay = round((strtotime($pageList->endTime) - strtotime(date('Y-m-d'))) / 3600 / 24) - $pageList->interestFrom + 1; //预期收益天数
                        $pageList->reduceDay = $pageList->reduceDay>0?$pageList->reduceDay:0;
                    }
                    unset($pageList->totalAmount,$pageList->interestFrom,$pageList->endTime,$pageList->onlineTime,$pageList->saleEndTime);//去除不需要的字段
                    $list[] = $pageList;
                }
                $data['pageNum'] = $results->result->pageNum;
            }
            $data['success']  = 1;
            $data['msg']      = '请求正常';
            $data['pagelist'] = $list;
        }
        $this->setResult($data);
    }

    /**
     * 理财项目
     */
    public function actionList()
    {
        $data = Project::model()->getProjectList();
        $this->setResult($data);
    }
    /**
     * 获取投资次数
     */
    private function  actiongetInvestedNum($id,$typeCode,$transferId=0,$category1=1)
    {
        $model = Project::model();
        if($transferId)
        {
            $oProject = Project::model()->findByPK($id);
            $typeCode = $oProject->category3;
            $category1 = $oProject->category1;
        }
        $num   = $model->getInvestedNum($id,$typeCode,$category1);
        $data  = array(
            'num'      => $num['num'],
            'success'  => 1,
            'msg'      => 'ok',
            'totalNum' => $num['investCount'],
        );
        if($transferId)
        {
            Project::model()->tranlistIni($transferId);
            $data['num'] = (int)Yii::app()->cache_new->llen('projectTransList.'.$transferId);
        }
        return $data;
    }
    /**
     * 已还款项目展示
     */
    public function actionOvered()
    {
        $this->render('overed');
    }
    /**
     * 转让列表
     */
    public function actionTransferList()
    {
        $data   = array('success'=>0);
        $remote = HttpLib::get($this->javaApi['transfer_list'],array(
            'page'  => $this->_post('page',1),
            'limit' => $this->_post('limit',5),
        ));
        if($remote->success)
        {
            $data['success']              = 1;
            $data['total']                = $remote->result->total;
            $data['successTransferCount'] = $remote->result->successTransferCount;
            $data['pageNum']              = $remote->result->pageNumber;
            $data['list']    = array();
            if($remote->result && $remote->result->projectList)
            {
                foreach($remote->result->projectList as $p)
                {
                    if($p->seasonProjectId)
                        continue;
                    $day = round( $p->saleEndTime/1000 - strtotime(date('Y-m-d')) ) / 3600 / 24 - $p->interestFrom + 1;
                    $data['list'][] = array(
                        'projectId'       => $p->projectId,
                        'projectName'     => $p->subTitle,
                        'isDiscount'      => $p->isDiscount,
                        'minInvestAmount' => $p->minInvestAmount,
                        'min_rate'        => number_format(100*$p->projectInterest,2,'.',''),
                        'reduceDay'       => $day>0?$day:0,
                    );
                }
            }
        }
        else
            $data['msg'] = $remote->errorMsg;
        $this->setResult($data);
    }

    /**
     * 转让项目详情
     */
    public function actionTransDetail()
    {
        $data = array('success' => 0);
        $id    = $this->_post('id');//project_id
        if(intval($id))
        {
            $model          = Project::model()->getTransByPK($id);
            $projectBalance = $model->projectBalance;
            $info  = array(
                'projectId'       => $model->projectId,//原始债券Id
                'name'            => $model->debtDTO->subTitle,
                'minInvestAmount' => $model->minInvestAmount,
                'incrementAmount' => $model->minInvestAmount,
                'interestFrom'    => $model->interestFrom,
                'statusCode'      => $model->statusCode,
                'profitType'      => $model->profitTypeName,
                'ratebegin'       => $model->projectInterest,//年化收益率最低值
                'projectBalance'  => $projectBalance,
                'process'         => $this->converPoint($projectBalance, $model->totalAmount),
                'investedNumber'  => $this->actiongetInvestedNum($model->projectId,$model->typeCode,$id),
                'totalAmount'     => number_format($model->totalAmount,0),
                'reduceDay'       => $model->reduceDay>0?$model->reduceDay:0,
                'discountRate'    => $model->discountRate,
                'withdrawTip'     => '项目还款日17:00到达您草根账户；申请提现下一工作日到达银行卡',
            );
            //解决缓存不一致
            if($projectBalance<=0 && $model->statusCode==4)
            {
                $info['statusCode'] = 8;
                Yii::app()->cache_new->hdel('transferProjectDetail',$id);
            }
            if( strtotime($model->saleEndTime) < time() && $model->statusCode==8)//解决缓存不一致
            {
                $info['statusCode'] = 9;
                Yii::app()->cache_new->hdel('transferProjectDetail',$id);
            }
            $info['linkName']  = '新人赠送'.Yii::app()->params['register_reward_bonus']['number'].'元新人礼包';
            $info['linkUrl']   = 'https://d5ds88.cgtz.com/version/notice/index';
            $info['linkTitle'] = '新手奖励';
            if($this->checkUserToken($this->_post('user_id'),TOKEN) )
            {
                $user = User::model();
                if($user->invested($this->_post('user_id')))
                {
                    $link = Yii::app()->cache_php->hget('MOBILE_APP_CONFIG','link');
                    if($link)
                    {
                        $link = json_decode($link);
                        if(strtotime($link->endTime) > time())
                        {
                            $info['linkName']  = $link->title;
                            $info['linkUrl']   = $link->url;
                            $info['linkTitle'] = $link->pageTitle;
                        }
                        else
                            unset($info['linkName'],$info['linkUrl']);
                    }
                    else
                        unset($info['linkName'],$info['linkUrl']);
                }
            }
            unset($model);
            $data['data']    = $info;
            $data['success'] = 1;
            $this->setResult($data);
        }
    }
}
